package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.query.TravelCommendQuery;
import cn.wolfcode.trip.base.query.TravelQuery;
import cn.wolfcode.trip.base.service.ITravelCommendService;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("travels")
public class TravelController {
    @Autowired
    private ITravelService travelService;
    @Autowired
    private ITravelCommendService commendService;
    @PostMapping
    public JSONResult save(Travel travel) {
        JSONResult result = new JSONResult();
        try {
            travel.setAuthor(UserContext.getCurrentUser());
            travelService.save(travel);
        }catch (Exception e){
            result.mark(e.getMessage());
        }
        return result;
    }

    @GetMapping("/{id}")
    public Travel getTravelById(@PathVariable Long id) {//该标签表示从路径拿id
        Travel travel = travelService.get(id);
        return travel;
    }

    @PutMapping
    public JSONResult updata(Travel travel) {
        JSONResult result = new JSONResult();
        try {
            travel.setAuthor(UserContext.getCurrentUser());
            travelService.update(travel);
        }catch (Exception e){
            result.mark(e.getMessage());
        }
        return result;
    }


    @GetMapping
    public Object list(TravelQuery qo){
        qo.setState(Travel.STATE_RELEASE);
        //只有公开的才能查询
        qo.setIsPublic(true);
        //根据更新时间排序
        qo.setOrderBy("t.releaseTime desc");
        PageInfo pageInfo = travelService.selectForList(qo);
        return pageInfo;
    }

    @GetMapping("/commends")
    public Object getTravelCommend(TravelCommendQuery qo){
        qo.setOrderBy("tc.schedule desc");
        return commendService.queryForApp(qo);
    }
}
